package com.linkturing.serial;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import com.linkturing.swing.XinhuaApplication;

import cn.hutool.core.convert.Convert;
import cn.hutool.log.Log;
import cn.hutool.log.LogFactory;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;

public class ReadSerialPortEventListener implements SerialPortEventListener {
	
	static Log log = LogFactory.get();
	
	//static Log log = Log.get(ReadSerialPortEventListener.class);
	
	SerialPort serialPort;
	int deviceNum = 0;
	public ReadSerialPortEventListener(SerialPort serialPort) {
		this.serialPort = serialPort;
	}
	
	public ReadSerialPortEventListener(SerialPort serialPort,int num) {
		this.serialPort = serialPort;
		deviceNum = num;
	}
	
    @Override
    public void serialEvent(SerialPortEvent arg0) {
        //对以下内容进行判断并操作
        /*
        BI -通讯中断
	    　　CD -载波检测
	    　　CTS -清除发送
	    　　DATA_AVAILABLE -有数据到达
	    　　DSR -数据设备准备好
	    　　FE -帧错误
	    　　OE -溢位错误
	    　　OUTPUT_BUFFER_EMPTY -输出缓冲区已清空
	    　　PE -奇偶校验错
        RI -　振铃指示
        */
        //switch多个，if单个
    	log.debug("serialEvent....."+arg0.getEventType());
    	System.out.println("serialEvent....."+arg0.getEventType());
    	if(arg0.getEventType()==SerialPortEvent.FE) {
    		log.debug("FE -帧错误");
    	}
        if (arg0.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        	
        	byte[] bt = readFromPort(serialPort);
        	log.debug("serialEvent.....deviceNum="+deviceNum+",数据长度="+bt.length);
        	log.debug("data="+Convert.toStr(bt));
        	System.out.println(Convert.toStr(bt));
        	System.out.println("serialEvent.....deviceNum="+deviceNum+",数据长度="+bt.length);
            try {
                /*if(bt.length==17) {
                	handleBiz(bt);
                }*/
                handleBiz(bt);
                
            } catch (Exception e) {
                e.printStackTrace();
            }
        } else {
        	log.error("称重机信号不可靠！");
        }
    }    
    
    private static String handleBiz(byte[] serialBuf) {
    	
    	ArrayList serialByte = new ArrayList();
    	StringBuffer Weight = new StringBuffer("0");
        String Byt_weight;
        String TareWeight="0";
        String Byt_tareWeight;
        
    	int dataSTX = serialBuf[0];   // 起始校验位
    	if(dataSTX == 2)
        {
            int dataA = serialBuf[1];     // 状态字A（小数点位置）
            int dataB = serialBuf[2];     // 状态字B（毛重/净重/超载）

            String str = bytesToHexString(serialBuf);
            str = str.toUpperCase();
            for(int i=0;i<str.length();i+=2)
            {
                String st = str.substring(i, i+2);
                serialByte.add(st);
            }
            for(int i=4;i<10;i++)
            {
                Byt_weight = (String)serialByte.get(i);
                if(Byt_weight.toCharArray()[1]!='0'||!Weight.toString().equals("0")){
                    Weight.append(Byt_weight.substring(1));
                }
            }
           
            switch (dataA) {
                case 0:Weight.delete(0,2);
                Weight.append("00");break;
                case 1:Weight.delete(0,1);
                Weight.append("0");break;
                case 2:break;
                case 3:Weight.insert(5,".");break;
                case 4:Weight.insert(4,".");break;
                case 5:Weight.insert(3,".");break;
                case 6:Weight.insert(2,".");break;
                case 7:Weight.insert(1,".");break;
                default: break;
            }
            
            //每次調用線程去刷新主頁面，防止主線程阻塞導致刷新很慢
            /*Thread t = new Thread(new Runnable() {
            	@Override
            	public void run() {
            		log.info(Weight.toString());
            		XinhuaApplication.textField_3.setText(String.valueOf(Integer.parseInt(Weight.toString())));
            	}
            	
            });
            t.start();*/
            
            XinhuaApplication.textField_3.setText(String.valueOf(Integer.parseInt(Weight.toString())));
            
            return Weight.toString();
        }
    	
    	return "0.00";
    }
    
    /** 
    * 从串口读取数据 
    *  
    * @param serialPort 
    *            当前已建立连接的SerialPort对象 
    * @return 读取到的数据 
    */  
    public static byte[] readFromPort(SerialPort serialPort) {  
    	
    	try {
    		//等待1毫秒，以便让数据读取完整
			Thread.sleep(50);
		} catch (InterruptedException e1) {
			e1.printStackTrace();
		}
    	
        InputStream in = null;  
        byte[] bytes = {};  
        try {  
            in = serialPort.getInputStream();  
            // 缓冲区大小为一个字节  
            int buflength = in.available();
              System.out.println("缓冲区大小:"+buflength);
            while (buflength > 0) {  
            	byte[] readBuffer = new byte[buflength];  
                int bytesNum = in.read(readBuffer);
                
                bytes = byteMerger(bytes, readBuffer);  
//                bytesNum = in.read(readBuffer);  
                buflength = in.available();
            }  
        } catch (IOException e) {  
            e.printStackTrace();  
            log.error("io出错");
        } finally { 
            try {  
                if (in != null) {  
                    in.close();  
                    in = null;  
                }  
//                serialPort.close();
            } catch (IOException e) {  
                e.printStackTrace();  
            }  
        }  
        return bytes;  
    } 
    
    
  //System.arraycopy()方法
    public static byte[] byteMerger(byte[] bt1, byte[] bt2){  
        byte[] bt3 = new byte[bt1.length+bt2.length];  
        System.arraycopy(bt1, 0, bt3, 0, bt1.length);  
        System.arraycopy(bt2, 0, bt3, bt1.length, bt2.length);  
        return bt3;  
    } 
    
    /**
     * 数组转换成十六进制字符串
     * @param bArray
     * @return HexString
     */
    public static final String bytesToHexString(byte[] bArray) {
        StringBuffer sb = new StringBuffer(bArray.length);
        String sTemp;
        for (int i = 0; i < bArray.length; i++) {
            sTemp = Integer.toHexString(0xFF & bArray[i]);
            if (sTemp.length() < 2)
                sb.append(0);
            sb.append(sTemp.toUpperCase());
        }
        return sb.toString();
    }

}
